# encoding=utf8
import os
from config import app, db
from flask import request, render_template
import flask.ext.whooshalchemy as whooshalchemy
from progressbar import ProgressBar
from sqlalchemy.orm import make_transient
from models import WebPage

whooshalchemy.whoosh_index(app, WebPage)


# start at 17:27 end in 18:01
def load():
    symbol = "_indexed_symbol"
    mark = "1"
    if os.path.exists(symbol):
        with open(symbol)as f:
            if f.read() == mark:
                return
    pages = WebPage.query.all()
    progress = ProgressBar()
    cnt = 0
    for p in progress(pages):
        db.session.delete(p)
        db.session.commit()
        cnt += 1
        if cnt % 10 == 0:
            print(p.id)
        make_transient(p)
        db.session.add(p)
        db.session.commit()
    with open(symbol, "w")as f:
        f.write(mark)


@app.route('/', methods=["GET"])
def search():
    args = request.args
    if "txtValue" in args:
        word = args['txtValue']
        print(word)
        results = WebPage.query.whoosh_search(word).all()
        print(len(results))
    else:
        results = None
    # results = WebPage.query.all()
    return render_template("index.html", pages=results)


if __name__ == '__main__':
    load()
    app.run(use_reloader=False)
